package Util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class DbConnector {

    private static final Logger logger = LogManager.getLogger(DbConnector.class);
    private static Connection conn;
    private static final String URL = "jdbc:mysql://localhost:3306/simpleBank?useSSL=false&serverTimezone=UTC";
    private static final String USER = "root";
    private static final String PASSWORD = "root";

    private DbConnector() {}

    public static Connection getConnection() throws SQLException{
        if (conn == null || conn.isClosed()) {
            try {
                conn = DriverManager.getConnection(URL, USER, PASSWORD);
            } catch (SQLException e) {
                logger.error("数据库连接失败", e);
                throw e;
            }
        }
        return conn;
    }

    public static void closeConnection() {
        if (conn != null) {
            try {
                conn.close();
                logger.info("数据库连接已关闭");
            } catch (SQLException e) {
                logger.error("关闭数据库连接失败", e);
            } finally {
                conn = null;
            }
        }
    }
}